/**
 * 
 *  JavaScript holding the google maps functionality.
 *   
 */


var DEFAULT_CENTER_LON = 21.2502;
var DEFAULT_CENTER_LAT = 48.7170;
var DEFAULT_ZOOM = 1;
var CROSSHAIR_IMG_ADDRESS = 'http://' + window.location.host + '/resources/target_icon.png';
var CROSSHAIR_IMG_RADIUS = 15;
var CENTER_MAP_INTERVAL = 60000;
var MARKER_WIDTH = 16;
var MARKER_HEIGHT = 16;

var map;
var crossHairMarker;
FriendsOverlay.prototype = new google.maps.OverlayView();
var infowindow = new google.maps.InfoWindow({
	disableAutoPan: true
});

/**
 * Initializes the OpenStreetMap component
 *
 * @param {Object} center_lon the longitude part of the center location
 * @param {Object} center_lat the latitude part of the center location
 * @param {Object} zoom the zoom level
 * @param {Object} div_id ID of the HTML div element, which will be the map component
 *
 * @author molnala
 */
function initOSM(center_lon, center_lat, zoom, div_id){

    if (div_id == undefined) 
        return; // TODO at least an error log!
    
    var mapInitTextElem = document.getElementById('mapInitText');
    if (mapInitTextElem) {
        document.getElementById(div_id).removeChild(mapInitTextElem);    
    }

    var center_lon = (center_lon != undefined) ? center_lon : DEFAULT_CENTER_LON;
    var center_lat = (center_lat != undefined) ? center_lat : DEFAULT_CENTER_LAT;
    var latlng = new google.maps.LatLng(center_lat, center_lon);
    var zoom = (zoom != undefined) ? zoom : DEFAULT_ZOOM;
    var myOptions = {
      zoom: 2,
      center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
	mapTypeControl: true,
	mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT},
	navigationControl: true
	//disableDefaultUI: true
	//navigationControlOptions: {style: google.maps.NavigationControlStyle.ANDROID}
    };
    map = new google.maps.Map(document.getElementById(div_id), myOptions);
 
    crossHairMarker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        icon: CROSSHAIR_IMG_ADDRESS
    });
    
    var layerFriends = new FriendsOverlay(map);
    
    google.maps.event.addListener(map, "center_changed", moveendEvent);
    google.maps.event.addListener(map, "click", removeInfoWindow);
 
    setInterval(setMapToCenter,CENTER_MAP_INTERVAL);
   
    return layerFriends;    
}

FriendsOverlay.prototype.setOverlay = function () {
	// Explicitly call setMap() on this overlay
	this.setMap(map);
}

FriendsOverlay.prototype.createFriendMarker = function (data) {
	this.markersArray_.push(data);
}

function FriendsOverlay(map) {
	// Now initialize all properties.
	//this.bounds_ = bounds;
	//this.image_ = image;
	this.map_ = map;
	this.markersArray_ = new Array();
	this.selectedMarker_ = null;
	
	// We define a property to hold the image's
	// div. We'll actually create this div
	// upon receipt of the add() method so we'll
	// leave it null for now.
	this.div_ = new Array();
}

FriendsOverlay.prototype.onAdd = function() {
	// Note: an overlay's receipt of onAdd() indicates that
	// the map's panes are now available for attaching
	// the overlay to the map via the DOM.
	for (var i = 0; i < this.markersArray_.length; i++) {
	  // Create the DIV and set some basic attributes.
	  var div = document.createElement('DIV');
	  div.style.border = "none";
	  div.style.borderWidth = "0px";
	  div.style.position = "absolute";
	  div.id = i;

	  // Create an IMG element and attach it to the DIV.
	  var img = document.createElement("img");
	  img.src = this.markersArray_[i].imgurl;
	  img.style.width = "100%";
	  img.style.height = "100%";
	  div.appendChild(img);
	  
	  div.onclick = function() {
			infowindow.setContent(layerFriends.markersArray_[this.id].popupContentHTML);
			infowindow.setPosition(new google.maps.LatLng(layerFriends.markersArray_[this.id].latitude, layerFriends.markersArray_[this.id].longitude));
			infowindow.open(map);
			layerFriends.selectedMarker_ = layerFriends.markersArray_[this.id];
			setMapToCenter();
		  };

	  // Set the overlay's div_ property to this DIV
	  this.div_.push(div);

	  // We add an overlay to a map via one of the map's panes.
	  // We'll add this overlay to the overlayImage pane.
	  var panes = this.getPanes();
	  panes.overlayLayer.appendChild(div);
	}
}

FriendsOverlay.prototype.draw = function() {
	for (var i = 0; i < this.div_.length; i++) {
	  // Size and position the overlay. We use a southwest and northeast
	  // position of the overlay to peg it to the correct position and size.
	  // We need to retrieve the projection from this overlay to do this.
	  var overlayProjection = this.getProjection();

	  // Retrieve the coordinates of this overlay
	  // in latlngs and convert them to pixels coordinates.
	  var location = overlayProjection.fromLatLngToDivPixel(new google.maps.LatLng(this.markersArray_[i].latitude, this.markersArray_[i].longitude));
	  
	  // Resize the image's DIV to fit the indicated dimensions.
	  var div = this.div_[i];
	  div.style.left = location.x + 'px';
	  div.style.top = location.y + 'px';
	  div.style.width =  MARKER_WIDTH + 'px';
	  div.style.height = MARKER_HEIGHT + 'px';
	}
}

FriendsOverlay.prototype.onRemove = function() {
	var parentNode = this.div_[0].parentNode;
	for (var i = 0; i < this.div_.length; i++) {
	  parentNode.removeChild(this.div_[i]);
	}
	  this.div_ = new Array();
}

FriendsOverlay.prototype.selectNextPopup = function(ascending) {
    if (ascending==undefined) {
        ascending = true;
    }
    var currentMarker = this.selectedMarker_;
    var nextMarker = undefined;   
    if (ascending) {
        for (var i = 0; i < this.markersArray_.length; i++) {
            if (currentMarker === this.markersArray_[i]) {
                var nextMarkerIndex = (i + 1) % this.markersArray_.length;
                nextMarker = this.markersArray_[nextMarkerIndex];
                break;
            }
        }
    }
    else {
        for (var i = this.markersArray_.length-1; i >= 0 ; i--) {
            if (currentMarker === this.markersArray_[i]) {
                var nextMarkerIndex = (this.markersArray_.length + i - 1) % this.markersArray_.length;
                nextMarker = this.markersArray_[nextMarkerIndex];
                break;
            }
        }
    }
    
    if (nextMarker) {
    	this.selectedMarker_ = nextMarker;
    	infowindow.setContent(this.selectedMarker_.popupContentHTML);
    	infowindow.setPosition(new google.maps.LatLng(this.selectedMarker_.latitude, this.selectedMarker_.longitude));
    	infowindow.open(map);
    }
}

FriendsOverlay.prototype.showMeAndMyFriend = function (userLon, userLat, uid) {
	if (userLon==null) {
		userLon = document.getElementById("input_lon").value;
	}
	if (userLat==null) {
		userLat = document.getElementById("input_lat").value;
	}
    if (userLon==null || userLat==null || uid==null) {
        return;
    }
	var marker = undefined;
	for (var i = 0; i < this.markersArray_.length; i++) {
        if (uid === this.markersArray_[i].uid) {
            marker = this.markersArray_[i];
            break;
        }
    }
	this.selectedMarker_ = marker;
	infowindow.setContent(this.selectedMarker_.popupContentHTML);
	infowindow.setPosition(new google.maps.LatLng(this.selectedMarker_.latitude, this.selectedMarker_.longitude));
	infowindow.open(map);
}

function removeInfoWindow() {
	infowindow.close();
}

function setMapToCenter() {
    if (map) {
	    var zoom = undefined; 
	    var center_lon = document.getElementById("input_lon").value;
	    var center_lat = document.getElementById("input_lat").value;
	    // set the center position and zoom level
	    map.setCenter(new google.maps.LatLng(center_lat, center_lon));
	    crossHairMarker.setPosition(map.getCenter());
    }
}

function moveendEvent(event){
	crossHairMarker.setPosition(map.getCenter());
    var lonLat = map.getCenter();
    document.getElementById("input_lat").value = lonLat.lat();
    document.getElementById("input_lon").value = lonLat.lng();  
}

//map move 
//not sure if it is needed
function map_move() {
	alert("Map move")
	var center_lon = document.getElementById("input_lon").value;
	var center_lat = document.getElementById("input_lat").value;
	// set the center position and zoom level
    map.setCenter(new google.maps.LatLng(center_lat, center_lon));
}
